package com.example.app3;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CardGameActivity extends AppCompatActivity {
    private GridView gridView;
    private TextView tvAttempts;
    private Button btnRestart;
    private GameModel gameModel;
    private CardAdapter adapter;
    private int currentHighScore;

    private List<Integer> cardImages = new ArrayList<>(Arrays.asList(
            R.drawable.card1,
            R.drawable.card2,
            R.drawable.cardback
    ));

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_card_game);

        currentHighScore = getIntent().getIntExtra("current_score", 0);

        gridView = findViewById(R.id.grid_view);
        tvAttempts = findViewById(R.id.tv_attempts);
        btnRestart = findViewById(R.id.btn_restart);

        gameModel = new GameModel(3, cardImages); // 3对卡牌，可调整数量
        adapter = new CardAdapter();
        gridView.setAdapter(adapter);

        gridView.setOnItemClickListener((parent, view, position, id) -> {
            if (gameModel.flipCard(position)) {
                adapter.notifyDataSetChanged();
                if (gameModel.getSecondFlippedCard() != null) {
                    tvAttempts.setText("尝试次数: " + gameModel.getAttempts());
                    new Handler().postDelayed(() -> {
                        boolean isMatch = gameModel.checkForMatch();
                        if (!isMatch) {
                            gameModel.resetFlippedCards();
                        } else {
                            if (gameModel.isGameOver()) {
                                Toast.makeText(CardGameActivity.this,
                                        "恭喜获胜！尝试次数: " + gameModel.getAttempts(),
                                        Toast.LENGTH_LONG).show();
                                Intent resultIntent = new Intent();
                                resultIntent.putExtra("score", gameModel.getAttempts());
                                setResult(RESULT_OK, resultIntent);
                            }
                            gameModel.resetFlippedCards();
                        }
                        adapter.notifyDataSetChanged();
                    }, 1000);
                }
            }
        });

        btnRestart.setOnClickListener(v -> {
            gameModel.restartGame();
            tvAttempts.setText("尝试次数: 0");
            adapter.notifyDataSetChanged();
        });
    }

    private class CardAdapter extends BaseAdapter {
        @Override
        public int getCount() { return gameModel.getCards().size(); }
        @Override
        public Object getItem(int position) { return gameModel.getCards().get(position); }
        @Override
        public long getItemId(int position) { return gameModel.getCards().get(position).getId(); }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if (convertView == null) {
                imageView = (ImageView) getLayoutInflater().inflate(R.layout.item_card, parent, false);
            } else {
                imageView = (ImageView) convertView;
            }

            Card card = gameModel.getCards().get(position);
            if (card.isFlipped() || card.isMatched()) {
                imageView.setImageResource(card.getImageResId());
            } else {
                imageView.setImageResource(R.drawable.cardback);
            }
            return imageView;
        }
    }
}